package com.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.common.constants.ProductConstants;
import com.mall.product.dao.AttrAttrgroupRelationDao;
import com.mall.product.dao.AttrGroupDao;
import com.mall.product.entity.*;
import com.mall.product.service.AttrAttrgroupRelationService;
import com.mall.product.service.AttrGroupService;
import com.mall.product.service.CategoryService;
import com.mall.product.vo.AttrRelationVo;
import com.mall.product.vo.AttrResponseVo;
import com.mall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.mall.product.dao.AttrDao;
import com.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存规格参数的信息
     * @param vo
     */
    @Override
    public void saveAttr(AttrVo vo) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(vo,entity);
        this.save(entity);
        if (vo.getAttrGroupId() != null && vo.getAttrType() == ProductConstants.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            relation.setAttrId(entity.getAttrId());
            relation.setAttrGroupId(vo.getAttrGroupId());
            attrAttrgroupRelationService.save(relation);
        }
    }

    /**
     * 根据catid进行分页查询
     * @param catelogId
     * @param params
     * @return
     */
    @Override
    public PageUtils queryBasePage(Long catelogId, Map<String, Object> params,String attrType) {
//        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
//        if (catelogId == 0){
//           wrapper.eq("catelog_id",catelogId);
//        }
        String key = (String) params.get("key");
//        if (StringUtils.isNotEmpty(key)){
//            wrapper.and(c ->{
//                c.eq("attr_id",key)
//                        .like("attr_name",key);
//            });
//        }
//        IPage<AttrEntity> page = this.page(
//                new Query<AttrEntity>().getPage(params),
//                wrapper
//        );
//        return new PageUtils(page);
        IPage<AttrEntity> page = this.lambdaQuery()
                .eq(catelogId != 0, AttrEntity::getCatelogId, catelogId)
                .eq(StringUtils.isNotEmpty(key), AttrEntity::getAttrId, key)
                .eq(attrType.equals("base"),AttrEntity::getAttrType,1)
                .eq(!attrType.equals("base"),AttrEntity::getAttrType,0)
                .or()
                .like(StringUtils.isNotEmpty(key), AttrEntity::getAttrName, key)
                .page(new Query<AttrEntity>().getPage(params));
        List<AttrEntity> records = page.getRecords();
        List<Object> list = records.stream().map(c -> {
            CategoryEntity entity = categoryService.getById(c.getCatelogId());
            AttrResponseVo vo = new AttrResponseVo();
            BeanUtils.copyProperties(c, vo);
            if (entity != null) {
                vo.setCatelogName(entity.getName());
            }
            if ("base".equalsIgnoreCase(attrType)) {
                AttrAttrgroupRelationEntity oned = attrAttrgroupRelationService.lambdaQuery()
                        .eq(AttrAttrgroupRelationEntity::getAttrId, c.getAttrId())
                        .one();
                if (oned != null && oned.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroup = attrGroupService.getById(oned.getAttrGroupId());
                    vo.setGroupName(attrGroup.getAttrGroupName());
                }
            }
            return vo;
        }).collect(Collectors.toList());
        PageUtils utils = new PageUtils(page);
        utils.setList(list);
        return utils;
    }

    /**
     * 查询
     * @param attrId
     * @return
     */
    @Override
    public AttrResponseVo getAttrInfo(Long attrId) {
        AttrResponseVo vo = new AttrResponseVo();
        AttrEntity byId = this.getById(attrId);
        BeanUtils.copyProperties(byId,vo);
        if (byId.getAttrType() == ProductConstants.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrId));
            if (relation != null) {
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(relation.getAttrGroupId());
                vo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
                vo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
        Long catelogId = byId.getCatelogId();
        Long[] logPath = categoryService.findCateLogPath(catelogId);
        vo.setCatelogPath(logPath);
        CategoryEntity entity = categoryService.getById(catelogId);
        if (entity != null){
            vo.setCatelogName(entity.getName());
        }
        return vo;
    }
    @Transactional
    @Override
    public void updateBaseAttr(AttrVo attr) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr, entity);
        this.updateById(entity);
        if (entity.getAttrType() == ProductConstants.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            relation.setAttrId(entity.getAttrId());
            relation.setAttrGroupId(attr.getAttrGroupId());
            Long attrId = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (attrId.intValue() > 0) {
                attrAttrgroupRelationDao.update(relation, new UpdateWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attr.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(relation);
            }
        }
    }

    /**
     * 根据类型删除
     * @param attrIds
     */
    @Override
    @Transactional
    public void removeByIdsDetails(Long[] attrIds) {
        for (Long attrId : attrIds) {
            AttrEntity byId = getById(attrId);
            if(byId != null && byId.getAttrType() == ProductConstants.AttrEnum.ATTR_TYPE_BASE.getCode()){
                // 还需要删除关联的属性中的中间表的信息
                attrAttrgroupRelationDao.delete(new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrId));
            }
        }
        // 1.删除属性表中的数据
        this.removeByIds(Arrays.asList(attrIds));
    }

    /**
     * 根据属性编号查询对应的基本信息
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> attrRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<AttrEntity> entityList = entities.stream().map((entity) -> {
            return this.getById(entity.getAttrId());
        }).filter(Objects::nonNull)
                .collect(Collectors.toList());
        return entityList;
    }

    /**
     * 解除属性组和基本属性的关联关系
     * @param vos
     */
    @Override
    public void deleteRelationn(AttrRelationVo[] vos) {
        List<AttrAttrgroupRelationEntity> list = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, entity);
            return entity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.removeBatchRelation(list);
    }

    /**
     * 根据属性得id查询出未关联的属性信息
     * @param attrgroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils getNoAttrRelationn(Long attrgroupId, Map<String, Object> params) {
        AttrGroupEntity entity = attrGroupService.getById(attrgroupId);
        Long catelogId = entity.getCatelogId();
        List<AttrGroupEntity> groupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupIds = groupEntities.stream().map(AttrGroupEntity::getCatelogId).collect(Collectors.toList());
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Long> longList = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("catelog_id",catelogId);
        wrapper.eq("attr_type", ProductConstants.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (!longList.isEmpty()){
            wrapper.notIn("attr_id",longList);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            QueryWrapper<AttrEntity> entityQuery = wrapper.and((w) -> {
                w.eq("attr_id", key)
                        .or()
                        .like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper);
        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        List<AttrEntity> list = this.lambdaQuery()
                .in(AttrEntity::getAttrId, attrIds)
                .eq(AttrEntity::getSearchType, 1)
                .list();
        List<Long> attrList = list.stream().map(AttrEntity::getAttrId).collect(Collectors.toList());
        return attrList;
    }
}